package com.kingmgg.kg_base.ui

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.kingmgg.kg_base.ext.saveAs
import com.kingmgg.kg_base.ext.saveAsUnChecked
import java.lang.reflect.ParameterizedType

/**
 *    Create by 金KingMgg  kingmgg
 *    on 2023/11/20 09:54
 *    程序人员写程序，又拿程序换酒钱
 *
 */
class BaseVmFragment<DB : ViewDataBinding, VM : BaseViewModel> : Fragment() {

    private lateinit var binding: DB
    private lateinit var vm: VM

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {

        val type = javaClass.genericSuperclass
        val vbClass: Class<DB> = type!!.saveAs<ParameterizedType>().actualTypeArguments[0].saveAs()
        val method = vbClass.getDeclaredMethod("inflate", LayoutInflater::class.java)
        binding = method.invoke(this, layoutInflater)!!.saveAsUnChecked()

        initVM()
        return binding.root
    }

    private fun initVM() {
        val argument = (this.javaClass.genericSuperclass as ParameterizedType).actualTypeArguments
        vm = ViewModelProvider(this).get(argument[1] as Class<VM>)
        activity?.let { vm.intoActivity(it) }
    }


}